<template>
    <p>
        Ask a yes/no question:
        <input v-model="question" :disabled="loading" />
    </p>
    <p>{{ answer }}</p>
</template>


<script>
import { ref } from 'vue'

export default {
    setup() {
         const question = ref('')
         const answer = ref('Questions usually contain a question mark. ;-)')
         const loading = ref(false)
        return { question, answer, loading }
    },
    watch: {
        async question(newQuestion, oldQuestion) {
            if (newQuestion.includes('?')) {
                this.loading = true
                this.answer = 'Thinking...'
                try {
                    const res = await fetch('https://yesno.wtf/api')
                    this.answer = (await res.json()).answer
                } catch (error) {
                    this.answer = 'Error! Could not reach the API. ' + error
                } finally {
                    this.loading = false
                }
            }
        }},
}

</script>